<template>
  <div class="box">
    <div class="title-box" v-if="$fieldShowFunc('52-cgddgl')">产品规格汇总</div>
    <div class="table-box" v-loading="tableLoading" v-if="$fieldShowFunc('52-cgddgl')">
      <!--  show-summary -->
      <el-table show-summary :summary-method="getSummaries" height="250" :header-cell-style="{
        background: '#FAFBFC',
        color: '#828A9D',
        textAlign: 'center',
      }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableDataGg">
        <el-table-column prop="product_specs_name" label="产品规格" show-overflow-tooltip
          v-if="$fieldShowFunc('cgjsd_cpgg')">
        </el-table-column>
        <el-table-column prop="num" label="产品数量" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_cpsl')">
        </el-table-column>
        <el-table-column prop="unit_price" label="采购单价" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_cgdj')">
          <template slot-scope="scope">
            {{ scope.row.unit_price }}元
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="结算金额" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_jsje2')">
          <template slot-scope="scope">
            {{ scope.row.total_price }}元
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="title-box">结算列表
      <div class="title-box-right">
        <div class="title-box-right-left">
          <p class="title-box-text">已选 <span>{{ multipleSelection.length }}</span>/20 数据</p>
          <el-button type="danger" plain class="title-box-right-left-btn" @click="removePurchaseSettlementSonFunc"
            :disabled="!multipleSelection.length" v-if="$isPer(permission, ['settlementList_del'])">移除</el-button>
        </div>
        <div class="title-box-right-right">
          <el-button type="primary" class="title-box-right-right-btn" @click="addCgOrderFunc"
            v-if="$isPer(permission, ['settlementList_add'])">添加采购订单</el-button>
          <el-button type="primary" class="title-box-right-right-btn" @click="hisListFunc"
            v-if="$isPer(permission, ['settlementList_hisList'])">操作历史</el-button>
        </div>
      </div>
    </div>
    <div class="table-box2" v-loading="tableLoading">
      <el-table ref="table" @row-click="handleHighlightChangeTable" :header-cell-style="{
        background: '#FAFBFC',
        color: '#828A9D',
        textAlign: 'center',
      }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableDataJs"
        @selection-change="handleSelectionChange" highlight-selection-row>
        <el-table-column type="selection" width="80"></el-table-column>
        <el-table-column prop="project_number" label="项目编号" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_xmbh')">
        </el-table-column>
        <el-table-column prop="project_name" label="项目名称" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_xmmc')">
        </el-table-column>
        <el-table-column prop="brand_name" label="品牌名称" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_ppmc')">
          <template slot-scope="scope">
            <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
              {{ scope.row.brand_name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_type" label="采购类型" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_cglx')">
          <template slot-scope="scope">
            <span v-if="scope.row.purchase_type == 1">项目采集</span>
            <span v-if="scope.row.purchase_type == 2">售后采集</span>
          </template>
        </el-table-column>
        <el-table-column prop="product_type_name" label="产品大类" show-overflow-tooltip
          v-if="$fieldShowFunc('cgjsd_cpdl')">
        </el-table-column>
        <el-table-column prop="product_specs_name" label="产品规格" show-overflow-tooltip
          v-if="$fieldShowFunc('cgjsd_cpgg2')">
        </el-table-column>
        <el-table-column prop="supplier_name" label="采购供应商" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_cggys')">
        </el-table-column>
        <el-table-column prop="created_at" label="下单时间" show-overflow-tooltip v-if="$fieldShowFunc('cgjsd_xdsj')">
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加采购订单 -->
    <el-dialog :modal-append-to-body="false" destroy-on-close title="添加采购订单" :visible.sync="addCgOrderShow"
      width="700px" :before-close="addCgOrderCancelFunc">
      <div class="add-scroll-view-box">
        <el-table ref="addTable" @row-click="addHandleHighlightChangeTable" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="addTableData"
          @selection-change="addHandleSelectionChange" highlight-selection-row>
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column prop="project_number" label="项目编号" show-overflow-tooltip v-if="$fieldShowFunc('cg_xmbh')">
          </el-table-column>
          <el-table-column prop="project_name" label="项目名称" show-overflow-tooltip v-if="$fieldShowFunc('cg_xmmc')">
          </el-table-column>
          <el-table-column prop="brand_name" label="品牌名称" show-overflow-tooltip v-if="$fieldShowFunc('cg_ppmc')">
            <template slot-scope="scope">
              <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
                {{ scope.row.brand_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="purchase_type" label="采购类型" show-overflow-tooltip v-if="$fieldShowFunc('cg_cglx')">
            <template slot-scope="scope">
              <span v-if="scope.row.purchase_type == 1">项目采集</span>
              <span v-if="scope.row.purchase_type == 2">售后采集</span>
            </template>
          </el-table-column>
          <el-table-column prop="product_type_name" label="产品大类" show-overflow-tooltip v-if="$fieldShowFunc('cg_cpdl')">
          </el-table-column>
          <el-table-column prop="product_specs_name" label="产品规格" show-overflow-tooltip
            v-if="$fieldShowFunc('cg_cpgg')">
          </el-table-column>
          <el-table-column prop="supplier_name" label="采购供应商" show-overflow-tooltip v-if="$fieldShowFunc('cg_cggys')">
          </el-table-column>
          <el-table-column prop="created_at" label="下单时间" show-overflow-tooltip v-if="$fieldShowFunc('cg_xdsj')">
          </el-table-column>

        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCgOrderSubmitFunc">提交</el-button>
        <el-button @click="addCgOrderCancelFunc">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 操作历史 -->
    <el-dialog :modal-append-to-body="false" destroy-on-close title="操作历史" :visible.sync="hisListShow" width="900px"
      :before-close="hisListCancelFunc">
      <div class="add-scroll-view-box">
        <el-empty description="无历史记录" v-if="!settlementOperateLogsList.length"></el-empty>
        <el-timeline class="timeline">
          <el-timeline-item v-for="(item, index) in settlementOperateLogsList" :key="index">
            <div class="setp-box">
              <div class="setp-top flex ac jb">
                <p class="time">{{ item.created_at }}</p>
                <div class="user-box flex ac">
                  <img class="avater" :src="item.image" />
                  {{ item.name + "-" + item.position }}
                </div>
              </div>
              <div class="setp-content">
                <p class="setp-content-title">{{ item.opera_status == 1 ? '新增' : '移除' }}采购订单</p>
                <el-table :header-cell-style="{
                  background: '#FAFBFC',
                  color: '#828A9D',
                  textAlign: 'center',
                }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="item.form_data">

                  <el-table-column min-width="180px" prop="project_number" label="项目编号" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_xmbh')">
                  </el-table-column>
                  <el-table-column min-width="180px" prop="project_name" label="项目名称" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_xmmc')">
                  </el-table-column>
                  <el-table-column min-width="180px" prop="brand_name" label="品牌名称" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_ppmc')">
                    <template slot-scope="scope">
                      <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
                        {{ scope.row.brand_name }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="180px" prop="purchase_type" label="采购类型" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_cglx')">
                    <template slot-scope="scope">
                      <span v-if="scope.row.purchase_type == 1">项目采集</span>
                      <span v-if="scope.row.purchase_type == 2">售后采集</span>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="180px" prop="product_type_name" label="产品大类" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_cpdl')">
                  </el-table-column>
                  <el-table-column min-width="180px" prop="product_specs_name" label="产品规格" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_cpgg')">
                  </el-table-column>
                  <el-table-column min-width="180px" prop="supplier_name" label="采购供应商" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_cggys')">
                  </el-table-column>
                  <el-table-column min-width="180px" prop="created_at" label="下单时间" show-overflow-tooltip
                    v-if="$fieldShowFunc('cg_xdsj')">
                  </el-table-column>

                </el-table>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="hisListCancelFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import purchaseApi from "@/api/purchaseApi";
export default {
  name: "settlementList",
  components: {},
  data() {
    return {
      tableLoading: false,
      userInfo: "",
      tableDataGg: [],//规格列表
      tableDataJs: [],//结算列表
      formSearch: {},
      page: 1,
      num: 10,
      total: 0,
      addLoading: false,
      pageLoading: false,
      multipleSelection: [],//列表多选结算列表
      // 添加采购订单
      addCgOrderShow: false,//弹窗显示
      addMultipleSelection: [],//多选列表采购订单
      addTableData: [],//采购订单列表
      // 历史记录
      hisListShow: false,//弹窗显示
      settlementOperateLogsList: [],//历史操作列表
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() { },
  mounted() {
    // 操作权限
    this.$getHtmlAuthority('/purchaseSettlementManagement').then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();
    this.getPurchaseSettlementInfo();//获取采购结算单详情列表
    this.getPurchaseSettlementInfoSpecs();//采购结算单详情产品规格汇总
  },
  methods: {
    // ----------------------------获取采购结算列表（未在结算单内的数据）----------------------------
    getPurchaseSettlementNewList() {
      purchaseApi.getPurchaseSettlementNewList({
        page: 1,
        num: 999,
        supplier_id: this.$route.query.supplier_id
      }).then(res => {
        console.log(res, "获取采购结算列表（未在结算单内的数据）")
        if (res.code == 200) {
          this.addTableData = res.data.list;
          this.addCgOrderShow = res.data.list.length != 0;
          if (!res.data.list.length) {
            this.$message({
              type: 'warning',
              message: "无采购订单数据"
            })
          }
        }
      })
    },
    // ----------------------------采购结算单详情产品规格汇总----------------------------
    getPurchaseSettlementInfoSpecs() {
      if (!this.$route.query.id) return;
      purchaseApi.getPurchaseSettlementInfoSpecs({ settlement_id: this.$route.query.id, }).then(res => {
        console.log(res, "采购结算单详情产品规格汇总")
        if (res.code == 200) {
          this.tableDataGg = res.data;
        }
      })
    },
    // ----------------------------获取采购结算单详情列表----------------------------
    getPurchaseSettlementInfo() {
      if (!this.$route.query.id) return;
      purchaseApi.getPurchaseSettlementInfo({
        settlement_id: this.$route.query.id,
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "获取采购结算单详情列表")
        if (res.code == 200) {
          this.tableDataJs = res.data.list;
        }
      })
    },
    // ----------------------------table选中事件----------------------------
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // ----------------------------table点击行-选中----------------------------
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // ----------------------------添加采购订单----------------------------
    addCgOrderSubmitFunc() {
      let addMultipleSelection = this.addMultipleSelection;
      console.log(addMultipleSelection)
      if (!addMultipleSelection.length) {
        this.$message({
          type: 'warning',
          message: "请先勾选采购订单"
        })
        return;
      }
      this.addedPurchaseSettlementSon();
    },
    // 手动添加采购结算单子表
    addedPurchaseSettlementSon() {
      let id_list = [];
      let addMultipleSelection = this.addMultipleSelection;
      addMultipleSelection.forEach(item => {
        id_list.push(item.purchase_info_id);
      })
      purchaseApi.addedPurchaseSettlementSon({
        settlement_id: this.$route.query.id,
        id_list
      }).then(res => {
        console.log(res, "手动添加采购结算单子表")
        if (res.code == 200) {
          this.getPurchaseSettlementInfo();
          this.getPurchaseSettlementInfoSpecs();
          this.addCgOrderCancelFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 添加采购订单开启
    addCgOrderCancelFunc() {
      this.addCgOrderShow = false;
      this.addMultipleSelection = [];
    },
    // 添加采购订单关闭
    addCgOrderFunc() {
      this.getPurchaseSettlementNewList();
    },
    // 采购订单table多选
    addHandleSelectionChange(e) {
      console.log(e);
      this.addMultipleSelection = e;
    },
    // 采购订单table多选
    addHandleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.addTable.toggleRowSelection(row);
      }
    },
    // ----------------------------历史记录----------------------------
    // 历史列表弹窗开启
    hisListFunc() {
      this.getPurchaseSettlementOperateLogs();
    },
    // 历史列表弹窗关闭
    hisListCancelFunc() {
      this.hisListShow = false;
    },
    // 获取采购结算操作日志
    getPurchaseSettlementOperateLogs() {
      purchaseApi.getPurchaseSettlementOperateLogs({
        settlement_id: this.$route.query.id
      }).then(res => {
        console.log(res, "获取采购结算操作日志")
        if (res.code == 200) {
          this.hisListShow = true;
          this.settlementOperateLogsList = res.data;
        }
      })
    },
    // 移除结算单
    removePurchaseSettlementSonFunc() {
      this.$confirm('此操作将永久删除勾选采购订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let multipleSelection = this.multipleSelection;
        let id_list = [];
        multipleSelection.forEach(item => {
          id_list.push(item.Id)
        })
        purchaseApi.removePurchaseSettlementSon({
          id_list,
          settlement_id: this.$route.query.id
        }).then(res => {
          console.log(res, "移除采购结算单子表")
          if (res.code == 200) {
            this.getPurchaseSettlementInfo();
            this.getPurchaseSettlementInfoSpecs();
          }
          this.$message({
            type: res.code == 200 ? 'success' : 'warning',
            message: res.message
          })
        })
      }).catch(() => {
      });
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.page = 1;
      this.getProjectList();
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch() {
      this.page = 1;
      this.getProjectList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.page = page;
      this.getProjectList();
    },
    addPurchaseFunc() { },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    getSummaries(param) {
      const { columns, data } = param;
      console.log(param)
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          index != 3 ? sums[index] : sums[index] += ' 元';
          sums[2] = '--';
        } else {
          sums[index] = '--';
        }
      });
      console.log(sums)
      return sums;
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>